package com.sc.VenusQueryBeta.ui.fragments.account.xiadaikuan;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.zhouwei.library.CustomPopWindow;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.PopAdapter;
import com.sc.VenusQueryBeta.adapter.account.xiadaikuan.XiaDaiKuan01Adapter;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.account.xiadaikuan.XiaDaiKuan01Contract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.account.CurrencyListBean;
import com.sc.VenusQueryBeta.model.bean.account.xiadaikuan.XiaDaiKuan01Bean;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.presenter.account.xiadaikuan.XiaDaiKuan01Presenter;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;

public class XiaDaiKuanFragment1 extends BaseMVPCompatFragment<XiaDaiKuan01Contract.XiaDaiKuan01Presenter> implements XiaDaiKuan01Contract.IXiaDaikuan01View {

    private static XiaDaiKuanFragment1 fragment;
    @BindView(R.id.ibtn_xiadaikuan_back)
    ImageButton ibtnXiadaikuanBack;
    @BindView(R.id.vip_uservip_user_infornation)
    RecyclerView rvxiadaikuan01;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.visible)
    TextView visible;
    @BindView(R.id.vip_user)
    TextView vipUser;
    @BindView(R.id.chooise_company)
    TextView chooiseCompany;
    @BindView(R.id.total_money)
    TextView totalMoney;
    private UsersLoginBean loginBean;
    private QueryRegisBean queryRegisBean;
    private int clientindex;
    private String roomname;
    private int roomid;
    private String name;
//    private View headView;
//    private View errorView;
//    private TextView btn_choose_club;
//    private TextView tv_jituan_money;
//    private TextView tv_time;
    private CustomPopWindow mClubPopWindow;
    private RecyclerView clubrecyclerView;
    private PopAdapter popAdapter;
    private CurrencyListBean mallRoomListBean;
    private boolean isUpdate = false;
    private XiaDaiKuan01Adapter xiaDaiKuan01Adapter;
    private String clientId;
    private String currency;
private XiaDaiKuan01Bean xiaDaiKuan01Bean;

    public static XiaDaiKuanFragment1 newInstance(QueryRegisBean queryRegisBean, int clientindex, String currency,String clientid,String clientnamecn) {
        Bundle args = new Bundle();
        args.putInt(Constants.CLIENTINDEX, clientindex);
        args.putSerializable(Constants.QUERY_SETTING, queryRegisBean);
        args.putString(Constants.CURRENCY_TYPE, currency);
//        args.putString(Constants.ROOMNAME, s);
        args.putString(Constants.ROOM_NAME, clientnamecn);
        args.putString(Constants.CLIENTID, clientid);
        fragment = new XiaDaiKuanFragment1();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    @Override
    public void initData() {
        super.initData();
        if (fragment.getArguments() != null) {
            loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
            queryRegisBean = (QueryRegisBean) fragment.getArguments().getSerializable(Constants.QUERY_SETTING);
            clientindex = fragment.getArguments().getInt(Constants.CLIENTINDEX, 0);
//            roomname = fragment.getArguments().getString(Constants.ROOMNAME);
            name = fragment.getArguments().getString(Constants.ROOM_NAME);
            clientId = fragment.getArguments().getString(Constants.CLIENTID);
            currency = fragment.getArguments().getString(Constants.CURRENCY_TYPE);
        }
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
            //查询所有厅

            mPresenter.queryAllCurrencyList(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort());
        } else {
            ToastUtils.showToast("数据异常");
        }
    }


    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return XiaDaiKuan01Presenter.newInstance();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_xia_dai_kuan_fragment1;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        chooiseCompany.setText(currency);
        vipUser.setText(clientId+"  "+name);
        xiaDaiKuan01Adapter = new XiaDaiKuan01Adapter(R.layout.item_xiadaikuan01);
        rvxiadaikuan01.setAdapter(xiaDaiKuan01Adapter);
        rvxiadaikuan01.setLayoutManager(new LinearLayoutManager(mContext));
//        vipUser.setText(clientId + " " + name);
//        initHeadView();
        initClub();
        reFreshListener();//下拉刷新
    }

    /**
     * 填充户口适配器\
     *
     * @param accountListBean
     */
    private void initRvList(final XiaDaiKuan01Bean accountListBean) {
        xiaDaiKuan01Adapter = new XiaDaiKuan01Adapter(R.layout.item_xiadaikuan01,accountListBean.getClientList());
        rvxiadaikuan01.setAdapter(xiaDaiKuan01Adapter);
        reFreshListener();//rv下拉刷新

    }

    /**
     * 下线贷款回电成功
     *
     * @param xiaDaiKuan01Bean
     */
    @Override
    public void showXiaDaikuanData1Success(XiaDaiKuan01Bean xiaDaiKuan01Bean) {
//        xiaDaiKuan01Adapter.removeAllHeaderView();
        //布局处理
        if (xiaDaiKuan01Bean.getClientList() != null && xiaDaiKuan01Bean.getClientList().size() > 0) {
            ptrClass.setVisibility(View.VISIBLE);
            visible.setVisibility(View.GONE);
            LogUtil.e("走了這裡嗎");
        } else {
            LogUtil.e("走了這裡嗎11111111");
//            xiaDaiKuanAdapter.setEmptyView(visible);
            ptrClass.setVisibility(View.GONE);
            visible.setVisibility(View.VISIBLE);
        }
//

        if (xiaDaiKuan01Adapter.getData().size() == 0) {
            initRvList(xiaDaiKuan01Bean);
        } else {
            if (isUpdate) {
                isUpdate = false;
                xiaDaiKuan01Adapter.setNewData(xiaDaiKuan01Bean.getClientList());
            } else {
                xiaDaiKuan01Adapter.addData(xiaDaiKuan01Bean.getClientList());
            }
        }
        chooiseCompany.setOnClickListener(new View.OnClickListener() {//选择集团監聽
            @Override
            public void onClick(View view) {
                mClubPopWindow.showAsDropDown(chooiseCompany, -20, 20);
            }
        });


//        xiaDaiKuan01Adapter.addHeaderView(headView);//动态添加头部布局
        totalMoney.setText(xiaDaiKuan01Bean.getClientList().get(0).getLoannumTotal() + getString(R.string.wan));
        ptrClass.refreshComplete();//
        hideProgressDialog();
    }

    @Override
    public void showNetworkError(Throwable throwable) {
        ptrClass.refreshComplete();//
//        xiaDaiKuanAdapter.setEmptyView(errorView);
        LogUtils.e("sdaddqweqweqweqeqw" + throwable);
        hideProgressDialog();
    }

    @Override
    public void showqueryAllCurrencyList(final CurrencyListBean currencyListBean) {
        if (currencyListBean.getCurrencys().size() > 0) {
//            roomid = Integer.parseInt(currencyListBean.getCurrencys().get(0).getRoomid());
            //填充廳數據
            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
            popAdapter = new PopAdapter(R.layout.pop_list_item, currencyListBean);
            clubrecyclerView.setAdapter(popAdapter);
            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            //集團點擊監聽
            popAdapter.setOnCliCkItemListenerr(new PopAdapter.OnCliCkItemListener() {
                @Override
                public void clickItem(int position) {
                    isUpdate = true;
//               roomid = Integer.parseInt(currencyListBean.getRoomList().get(position).getRoomid());
                    chooiseCompany.setText(currencyListBean.getCurrencys().get(position).getCurrencyName1());//動態改變集團名稱
                    //查詢子戶口
//                    xiaDaiKuan01Adapter.removeAllHeaderView();
                    showProgressDialog("請稍等...");
                    mPresenter.getXiaDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, chooiseCompany.getText().toString());
                    mClubPopWindow.dissmiss();
                }
            });
            mallRoomListBean = currencyListBean;
//            //查询子户口
            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
                //查询下线贷款
                showProgressDialog("請稍等...");
                isUpdate = true;
                LogUtils.e("roomid=========" + roomid);
                mPresenter.getXiaDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, chooiseCompany.getText().toString());
            } else {
                hideProgressDialog();
            }
        }
    }

//    @Override
//    public void showqueryAllRoomList(final AllRoomListBean allRoomListBean) {
//        if (allRoomListBean.getRoomList().size() > 0) {
//            roomid = Integer.parseInt(allRoomListBean.getRoomList().get(0).getRoomid());
//            //填充廳數據
//            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recycleview
//            popAdapter = new PopAdapter(R.layout.pop_list_item, allRoomListBean.getRoomList());
//            clubrecyclerView.setAdapter(popAdapter);
//            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
//            //集團點擊監聽
//            popAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                @Override
//                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                    roomid = Integer.parseInt(allRoomListBean.getRoomList().get(position).getRoomid());
//                    btn_choose_club.setText(allRoomListBean.getRoomList().get(position).getRoomname());//動態改變集團名稱
//                    //查詢子戶口
//                    xiaDaiKuan01Adapter.removeAllHeaderView();
//                    showProgressDialog("請稍等...");
//                    mPresenter.getXiaDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
//                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, roomid);
//                    mClubPopWindow.dissmiss();
//                }
//            });
//            mallRoomListBean = allRoomListBean;
////            //查询子户口
//            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
//                //查询下线贷款
//                showProgressDialog("請稍等...");
//                LogUtils.e("roomid=========" + roomid);
//                mPresenter.getXiaDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
//                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, roomid);
//            } else {
//                hideProgressDialog();
//            }
//        }
//    }

//    /**
//     * 初始化头部
//     */
//    private void initHeadView() {
//        if (headView == null) {
//            headView = ResourcesUtils.inflate(R.layout.rv_top);
//        }
//        if (errorView == null) {
//            errorView = ResourcesUtils.inflate(R.layout.view_network_error);
//        }
//        errorView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mPresenter.getXiaDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
//                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, roomid);
//            }
//        });
////        btn_choose_club = headView.findViewById(R.id.chooise_company);
//        tv_jituan_money = headView.findViewById(R.id.total_money);
//        tv_time = headView.findViewById(R.id.chooise_time);
//        tv_time.setVisibility(View.INVISIBLE);
//
//    }

    private void initClub() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_list, null);
        //处理popWindow 显示内容

        //创建并显示popWindow
        mClubPopWindow = new CustomPopWindow.PopupWindowBuilder(mActivity)
                .setView(contentView)
                .create();
        clubrecyclerView = contentView.findViewById(R.id.recyclerView);

    }

    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mContext);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部

        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                      mAdapterWithHF.notifyDataSetChanged();//适配器更新数据
                        if (mPresenter != null && ptrClass != null) {
                            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
                                isUpdate = true;
                                showProgressDialog("請稍等...");
                                mPresenter.getXiaDaiKuan01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, chooiseCompany.getText().toString());
                            } else {
                                ToastUtils.showToast("数据异常");
                            }
                        } else {
                            hideProgressDialog();
                        }
                        if (ptrClass != null) {
                            ptrClass.refreshComplete();
                        } else {
                            hideProgressDialog();
                        }
                    }
                }, 1000);
            }
        });
    }




    @OnClick({R.id.ibtn_xiadaikuan_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_xiadaikuan_back:
                pop();
                break;

        }
    }
}
